#include "qpixmapmeger.h"

#include <QLineEdit>
#include <QPainter>
#include <QTextEdit>

QPixmapMeger::QPixmapMeger(QObject *parent)
    : QObject{parent}
{

}

QPixmap QPixmapMeger::pixmap_merge(const QPixmap &pixmap1, const QPixmap &pixmap2, bool vertical, bool right) {
    // 计算合并后的尺寸
    int width_h = pixmap1.width() + pixmap2.width() + 6; // 水平合并的宽度
    int height_h = qMax(pixmap1.height(), pixmap2.height()); // 水平合并的高度

    int width_v = qMax(pixmap1.width(), pixmap2.width()); // 垂直合并的宽度
    int height_v = pixmap1.height() + pixmap2.height() + 6; // 垂直合并的高度

    // 创建合并后的 QPixmap
    QPixmap mergedPixmap(vertical ? width_v : width_h, vertical ? height_v : height_h);
    mergedPixmap.fill(Qt::lightGray); // 背景填充为浅灰色

    QPainter painter(&mergedPixmap);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制分割线
    QRect lineRect;
    if (vertical) {
        lineRect.setTopLeft(QPoint(0, pixmap1.height() + 2));
        lineRect.setTopRight(QPoint(width_v, pixmap1.height() + 2));
    } else {
        lineRect.setTopLeft(QPoint(pixmap1.width() + 2, 0));
        lineRect.setBottomLeft(QPoint(pixmap1.width() + 2, height_h));
    }

    if (vertical) {
        painter.drawLine(lineRect.topLeft(), lineRect.topRight());
    } else {
        painter.drawLine(lineRect.topLeft(), lineRect.bottomLeft());
    }

    // 绘制 pixmap1 和 pixmap2
    if (vertical) {
        painter.drawPixmap(QPoint(0, 0), pixmap1);
        if (right) {
            painter.drawPixmap(QPoint(pixmap1.width() - pixmap2.width(), pixmap1.height() + 6), pixmap2);
        } else {
            painter.drawPixmap(QPoint(0, pixmap1.height() + 6), pixmap2);
        }
    } else {
        painter.drawPixmap(QPoint(0, 0), pixmap1);
        painter.drawPixmap(QPoint(pixmap1.width() + 6, 0), pixmap2);
    }

    return mergedPixmap;
}

QPixmap QPixmapMeger::pixmap_merge_v3(const QPixmap &pixmap1, const QPixmap &pixmap2, const QPixmap &pixmap3, bool vertical) {
    return pixmap_merge(pixmap_merge(pixmap1, pixmap2, vertical), pixmap3, vertical, true);
}

QPixmap QPixmapMeger::pixmap_from_textedit(const QTextEdit *textedit)
{
    QSize size = textedit->document()->size().toSize();

    QPixmap pixmap(size);
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);
    textedit->document()->drawContents(&painter);

    return pixmap;
}

QPixmap QPixmapMeger::pixmap_from_lineedit(const QLineEdit *lineedit)
{
    QFontMetrics metrics(lineedit->font());
    QString text = lineedit->text();

    QSize size = metrics.size(Qt::TextSingleLine, text);

    QPixmap pixmap(size);
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);
    painter.drawText(pixmap.rect(), text);

    return pixmap;
}
